<template>
  <NuxtLayout>
    <div class="con">
      <div class="con-cen">
        <el-descriptions border title="基本信息" :column="2">
          <el-descriptions-item label="所属科目">{{ infoData.subject ? infoData.subject.name : '-' }}</el-descriptions-item>
          <el-descriptions-item label="课程讲师">{{ infoData.teacher ? infoData.teacher.name : '-' }}</el-descriptions-item>
          <el-descriptions-item label="购买课程">{{ infoData.title }}</el-descriptions-item>
          <el-descriptions-item label="购买金额"><span class="red">￥{{ infoData.amount }}</span></el-descriptions-item>
        </el-descriptions>
        <br>
        <el-tabs class="pay-tab" v-model="tabValue" @tab-click="tabClickFn" stretch>
          <el-tab-pane label="微信支付" name="1">
            <el-image :src="wechatPayUrl" class="pay-qrocde"></el-image>
            <div class="pay-downtime">{{ downTime }}s</div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </NuxtLayout>
</template>

<script setup>
import { getLessonInfoApi, lessonPurchaseApi, nativepay, hasPurchase } from "~/server/api";
import { useCountStore } from "~/store/counter.js";
useCountStore().$patch({ indexActive: 3 });
// 验证路由
definePageMeta({
  validate: async (route) => {
    return /^1\d{5,}$/.test(route.params.courseId);
  }
})
// TDK
const prevHost = useRequestHeaders()["x-forwarded-proto"];
const host = useRequestHeaders()["host"];
const fullPath = useRoute()["fullPath"];
const seoTitle = ref("技考邦_交易中心");
const seoKeywords = ref("技考邦,交易中心");
const seoDescription = ref("技考邦，交易中心");
const courseId = useRoute().params.courseId || '';
const infoData = ref({});
const orderNum = ref('');
const wechatPayUrl = ref('');
const tabValue = ref('1')
const downTime = ref(60)
const timer = ref(null)
// 获取课程信息
async function getCourse() {
  let { data: infoRes } = await useAsyncData(() => useServerRequest(getLessonInfoApi, {
    method: 'get',
    params: { courseId }
  }))
  if (infoRes.value && infoRes.value.errno === 0 && infoRes.value.result) {
    infoData.value = infoRes.value.result;
    seoTitle.value = `${infoData.value.title}_购买课程_交易中心`;
    seoKeywords.value = `购买课程,交易中心`;
    seoDescription.value = `购买技考邦${infoData.value.title}等更多课程`;
    return false;
  }
  showError({ statusCode: 404, statusMessage: `Page not found: ${useRoute().path}` });
}
getCourse()
// 获取订单号
async function getOrder() {
  let { data: orderRes } = await useAsyncData(() => useServerRequest(lessonPurchaseApi, {
    method: 'post',
    body: JSON.stringify({ id: courseId })
  }))
  if (orderRes.value && orderRes.value.errno === 0 && orderRes.value.result) {
    orderNum.value = orderRes.value.result;
  }
}
getOrder()
// 获取微信支付地址
async function getWechatPay(orderNo) {
  let payRes = await useServerRequest(nativepay, {
    method: 'get',
    params: { orderNo }
  })
  if (payRes && payRes.errno === 0 && payRes.result) {
    wechatPayUrl.value = `https://api.jkb100.com/api/qr.png?content=${payRes.result}`;
    if (localStorage.getItem('payTime')) {
      downTime.value = localStorage.getItem('payTime');
    }
    if (timer.value) {
      clearInterval(timer.value)
      timer.value = null;
    }
    payDownTime()
  }
}
// 获取是否购买课程
async function getPayCourse() {
  let flag = false;
  let res = await useServerRequest(hasPurchase, {
    method: 'post',
    body: JSON.stringify({
      id: courseId
    })
  })
  if (res && res.errno === 0) {
    flag = res.result;
  }
  return flag;
}
// 切换支付方式
function tabClickFn(e) {
  tabValue.value = e.props.name;
}
// 支付倒计时
function payDownTime() {
  let downtimeFlag = false;
  timer.value = setInterval(async () => {
    if (downTime.value < 1 || downtimeFlag) {
      clearInterval(timer.value)
      timer.value = null;
      localStorage.removeItem('payTime')
      downTime.value = 60;
      window.location.href = `/curriculum_details/${courseId}.html`;
      if (downtimeFlag) {
        ElMessage.success('购买成功')
      } else {
        ElMessage.warning('长时间未操作，返回课程详情')
      }
      return false
    }
    downTime.value--;
    localStorage.setItem('payTime', downTime.value)
    downtimeFlag = await getPayCourse();
  }, 1000)
}
// 挂载后
onMounted(() => {
  getWechatPay(orderNum.value)
})
// TDK
useSeoMeta({
  title: seoTitle,
  keywords: seoKeywords,
  description: seoDescription,
  ogTitle: seoTitle,
  ogDescription: seoDescription,
  ogType: "article",
  ogUrl: `${prevHost}://${host}${fullPath}`,
});
</script>

<style lang="less">
.pay-tab {
  text-align: center;

  .el-tabs__item {
    font-size: 16px;
  }
}
</style>
<style lang="less" scoped>
.con {
  padding: 20px 0;
  min-height: calc(100vh - 454px);

  &-cen {
    width: 800px;
    margin: 0 auto;
    background: #ffffff;
    border-radius: 10px;
    border: 1px solid #eaeae6;
    padding: 20px;

    .pay-qrocde {
      width: 180px;
      height: 180px;
    }

    .pay-downtime {
      color: #999;
      font-size: 14px;
    }
  }
}

.red {
  color: #FF3F29;
}
</style>